<template>
  <div class="signup-page mx-auto p-3 w-330">
    <ValidateFrom @form-submit="onFormSubmit">
      <template #default>
        <div class="mb-3">
          <label class="form-label">邮箱地址</label>
          <validate-input :rules="emailRules" v-model="info.email" tag="input" id="signup-email"></validate-input>
        </div>
        <div class="mb-3">
          <label class="form-label">昵称</label>
          <validate-input :rules="nickNameRules" v-model="info.nickName" tag="input" id="signup-nick-name">
          </validate-input>
        </div>
        <div class="mb-3">
          <label class="form-label">密码</label>
          <validate-input :rules="passwordRules" v-model="info.password" tag="input" type="password"
            id="signup-password"></validate-input>
        </div>
        <div class="mb-3">
          <label class="form-label">确认密码</label>
          <validate-input :rules="repeatPasswordRules" v-model="info.repeatPassword" tag="input" type="password"
            id="signup-repeat-password">
          </validate-input>
        </div>
      </template>
      <template #submit>
        <button type="submit" class="btn btn-primary d-block w-100">注册</button>
      </template>
    </ValidateFrom>
  </div>
</template>
<script setup lang="ts">
import { reactive } from 'vue';
import ValidateFrom from '../components/ValidateFrom.vue';
import ValidateInput, { type RuleProp } from '../components/ValidateInput.vue';
import { reqCreateInfo } from '../api/request';
import { useRouter } from 'vue-router';
import createMessage from '../components/createMessage';
const info = reactive({
  email: '',
  nickName: '',
  password: '',
  repeatPassword: ''
})
// 邮箱
const emailRules: RuleProp[] = [
  { type: 'required', message: '电子邮箱不能为空' },
  { type: 'email', message: '请输入正确电子邮箱地址' },
]
// 昵称
const nickNameRules: RuleProp[] = [
  { type: 'required', message: '昵称不能为空' },
]
// 密码
const passwordRules: RuleProp[] = [
  { type: 'required', message: '密码不能为空' },
]
// 确认密码
const repeatPasswordRules: RuleProp[] = [
  { type: 'required', message: '密码不能为空' },
  {
    type: 'custom', message: '密码不相同',
    validator: () => {
      return info.password === info.repeatPassword
    }
  }
]
const router = useRouter()
const onFormSubmit = (result: boolean) => {
  if (result) {
    reqCreateInfo({ email: info.email, nickName: info.nickName, password: info.password }).then(() => {
      createMessage('注册成功正在跳转', 'success')
      setTimeout(() => {
        router.push('/login')
      }, 2000);
    }).catch(err => {
      console.log(err);

    })
  }
}
</script>